package com.bilibili.server.service;

import com.bilibili.server.dto.AuthResponse;
import com.bilibili.server.dto.RegisterRequest;
import com.bilibili.server.entity.User;
import com.bilibili.server.repository.UserRepository;
import com.bilibili.server.security.CustomUserDetailsService;
import com.bilibili.server.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CustomUserDetailsService userDetailsService;

    // 用户注册
    public AuthResponse register(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        Optional<User> existingUser = userRepository.findByUsername(registerRequest.getUsername());
        if (existingUser.isPresent()) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        Optional<User> existingEmail = userRepository.findByEmail(registerRequest.getEmail());
        if (existingEmail.isPresent()) {
            throw new RuntimeException("邮箱已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setNickname(registerRequest.getUsername()); // 默认昵称与用户名相同
        user.setRole(User.Role.user); // 默认角色为普通用户
        user.setStatus(1); // 默认状态为激活

        // 保存用户
        User savedUser = userRepository.save(user);

        // 生成JWT Token
        UserDetails userDetails = userDetailsService.loadUserByUsername(savedUser.getUsername());
        String token = jwtUtil.generateToken(userDetails);

        return new AuthResponse(token, savedUser);
    }

    // 用户登录
    public AuthResponse login(String username, String password) {
        // 认证用户
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
        );

        // 生成JWT Token
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtUtil.generateToken(userDetails);

        // 获取用户信息
        Optional<User> userOptional = userRepository.findByUsernameAndStatus(username, 1);
        User user = userOptional.orElseThrow(() -> new RuntimeException("用户不存在") );

        return new AuthResponse(token, user);
    }

    // 获取当前用户信息
    public User getCurrentUser(String username) {
        Optional<User> userOptional = userRepository.findByUsernameAndStatus(username, 1);
        return userOptional.orElseThrow(() -> new RuntimeException("用户不存在") );
    }

    // 修改密码
    public void changePassword(String username, String oldPassword, String newPassword) {
        // 获取用户
        User user = userRepository.findByUsernameAndStatus(username, 1)
                .orElseThrow(() -> new RuntimeException("用户不存在") );

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("旧密码错误");
        }

        // 更新新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
    }
}